package com.xt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xt.bean.Library;
import com.xt.dao.LibraryRepository;
import com.xt.dto.LibraryListSearchDto;
import com.xt.service.LibraryService;
import com.xt.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by XT on 2018/5/4.
 */
@Service
public class LibraryServiceImpl implements LibraryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private LibraryRepository lr;

    @Value("${spider.library}")
    private String SPIDER_LIBRARY;

    @Value("${spider.library.fields}")
    private String SPIDER_LIBRARY_FIELDS;

    @Override
    public void saveOrUpdateOne(Library a) {

        if (StringUtils.isEmpty(a.getId())) {
            //新增
            a.setCreateDate(new Date());
        }

        a.setUpdateDate(new Date());
        lr.save(a);
    }

    @Override
    public void deleteOne(String id) {
        //删除关联关系

        lr.delete(id);
    }

    @Override
    public Library getById(String id) {
        return lr.findOne(id);
    }

    @Override
    public Page<Library> getPage(LibraryListSearchDto dto) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        //模糊查询
        criteria.and("bookName").regex(".*?" + dto.getBookName() + ".*", "i");
        criteria.and("bookOrigin").regex(".*?" + dto.getBookOrigin() + ".*");
        query.addCriteria(criteria);

        Pageable pa = PageUtil.getPageable(dto.getCount(), dto.getPageNo(), dto.getSortDirection(), dto.getSortField());
        //查询出一共的条数
        Long count = mongoTemplate.count(query, Library.class);

        //如果没有相关的图书，则调用一次爬虫
        if(count <= 0) {
            requestSpiderLibrary(dto);
        }

        count = mongoTemplate.count(query, Library.class);
        //查询
        List<Library> list = mongoTemplate.find(query.with(pa), Library.class);
        //将集合与分页结果封装
        Page<Library> pagelist = new PageImpl<Library>(list, PageUtil.getPageable(dto.getCount(), dto.getPageNo(), dto.getSortDirection(), dto.getSortField()), count);

        return pagelist;
    }

    private void requestSpiderLibrary(LibraryListSearchDto dto) {
            RestTemplate restTemplate = new RestTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            JSONObject jo = new JSONObject();
            jo.put("searchName",dto.getBookName());
            jo.put("pn","1");
            jo.put("t_id", UUID.randomUUID().toString());
            HttpEntity requestEntity = new HttpEntity<>(jo.toJSONString(), headers);

            ResponseEntity<String> response = null;
            try {
                response = restTemplate.exchange(
                        SPIDER_LIBRARY,
                        HttpMethod.POST,
                        requestEntity,
                        String.class);

                if ("200".equals(response.getStatusCode())){

                }
            } catch (Exception e) {
                throw e;
            }
    }

}

